package com.nstskj.study.netty.tcp.netty.protocol.handler.msg.strategy.impl;

import com.nstskj.study.netty.tcp.netty.protocol.handler.msg.ProtocolHandler;
import com.nstskj.study.netty.tcp.netty.protocol.handler.msg.strategy.ProtocolHandlerStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author ZhouChuGang
 * @version 1.0
 * @project nstskj-study-netty-tcp-spring
 * @date 2021/4/20 21:39
 * @Description
 */
@Slf4j
@Component
public class SpringProtocolHandlerStrategy implements ProtocolHandlerStrategy, BeanPostProcessor {

    private final Map<Short, ProtocolHandler> handlerConcurrentHashMap = new ConcurrentHashMap<>();

    @Override
    public ProtocolHandler getProtocolHandler(short cmd) {
        return handlerConcurrentHashMap.get(cmd);
    }

    /**
     * 在bean初始化之前执行
     * 这里得到容器中所有的处理类 并放入缓存中
     *
     * @param bean
     * @param beanName
     * @return
     * @throws BeansException
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof ProtocolHandler) {
            ProtocolHandler handler = (ProtocolHandler) bean;
            handlerConcurrentHashMap.put(handler.supportCmd(), handler);
        }
        return null;
    }
}
